#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QPushButton>
#include <QTextEdit>
#include <QLabel>
#include <QMessageBox>
#include <QDebug>
#include <QFile>
#include <QTextStream>
#include <QCoreApplication>
#include "../src/prescriptionchecker_export.h"

class MainWindow : public QWidget
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr) : QWidget(parent)
    {
        setupUI();
        setupConnections();
    }

private slots:
    void onCheckButtonClicked()
    {
        QString xmlData = m_xmlEdit->toPlainText();
        if (xmlData.isEmpty()) {
            QMessageBox::warning(this, "警告", "请输入XML数据");
            return;
        }
        
        m_statusLabel->setText("正在检查处方...");
        m_checkButton->setEnabled(false);
        
        // 使用C风格API
        QByteArray xmlBytes = xmlData.toUtf8();
        int result = DoctorCheck(xmlBytes.constData(), [](const char* data) {
            qDebug() << "数据回调:" << data;
        });
        
        if (result == 0) {
            m_statusLabel->setText("检查请求已发送，请等待结果...");
        } else {
            m_statusLabel->setText("检查请求发送失败");
            m_checkButton->setEnabled(true);
        }
    }

private:
    void setupUI()
    {
        setWindowTitle("处方检查工具");
        setFixedSize(600, 500);
        
        QVBoxLayout* layout = new QVBoxLayout(this);
        
        // XML输入区域
        QLabel* xmlLabel = new QLabel("XML处方数据:", this);
        layout->addWidget(xmlLabel);
        
        m_xmlEdit = new QTextEdit(this);
        m_xmlEdit->setPlaceholderText("请在此输入XML格式的处方数据...");
        m_xmlEdit->setMaximumHeight(300);
        layout->addWidget(m_xmlEdit);
        
        // 检查按钮
        m_checkButton = new QPushButton("检查处方", this);
        layout->addWidget(m_checkButton);
        
        // 状态标签
        m_statusLabel = new QLabel("准备就绪", this);
        layout->addWidget(m_statusLabel);
        
        // 加载示例XML
        loadExampleXML();
    }
    
    void setupConnections()
    {
        connect(m_checkButton, &QPushButton::clicked, this, &MainWindow::onCheckButtonClicked);
    }
    
    void loadExampleXML()
    {
        // 尝试从应用程序目录加载input.xml文件
        QString xmlFilePath = QCoreApplication::applicationDirPath() + "/input.xml";
        QFile xmlFile(xmlFilePath);
        
        // 如果应用程序目录下没有，尝试从项目根目录加载
        if (!xmlFile.exists()) {
            xmlFilePath = "input.xml";
            xmlFile.setFileName(xmlFilePath);
        }
        
        if (xmlFile.exists() && xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&xmlFile);
            in.setEncoding(QStringConverter::Utf8);
            QString xmlContent = in.readAll();
            xmlFile.close();
            
            m_xmlEdit->setPlainText(xmlContent);
            m_statusLabel->setText("已加载 input.xml 文件");
            qDebug() << "成功从文件加载XML:" << xmlFilePath;
        } else {
            // 如果文件不存在或无法打开，使用默认示例XML
            qDebug() << "无法加载input.xml文件，使用默认示例XML";
            
            QString exampleXML = R"(<checkInput tag="1" hospitalId="" branchId="" inpatient="2" prescType="0" >
<doctor id="ZY10282" name="李先清" title="副主任医师" deptName="NICU" deptCode="919" />
<patient name="王国亮" id="0003216994" visitId="001" patientPresId="20170823903005" birth="20000818" height="160" weight="80" gender="女" pregnant="是" lact="是" hepatical="是" renal="是" pancreas="是" alergyDrugs="花粉过敏" identityType="" feeType="西药费" scr="100" scrUnit="ml" gestationWeek="" pretermBirth="" wardCode="" wardName="" bedNo="" inpatientNo="" clinicType="支付宝" clinicLabel="" />
<diagnosises diagnosises="皮肤过敏、过敏" />
<advices >
        <advice drugLoId="67036" drugLoName="麝香追风止痛膏" adminRoute="口服" dosage="100" doseUnit="贴" freqCount="3" freqInterval="1" freqIntervalUnit="日"  startDay="20250709" endDay="" repeat="" orderNo="1" orderSubNo="1" deptCode="919" deptName="NICU" doctorId="ZY10282" doctorName="李先清" doctorTitle="副主任医师" authorityLevel="" authorityAlertLevel="" groupId="1" presId="20170823903003" presDate="20250709" course="7" pkgCount="2000" pkgUnit="盒" bak01="" bak02="" drugForm="" drugSpec="7cm×10cm*4贴" drugProducer="重庆希尔安药业有限公司" time="" skinTest="" skinTestResult="" instructDrugSpeed="10" instructDrugSpeedUnit="mg" lastPrescDate="" lastDeptName="" lastDoctorName="" onlineStatus="" drugUseDays="" remainingDays="" preventiveMedication="" pharmacyCode="123" pharmacyName="123" />
</advices>
</checkInput>)";
            
            m_xmlEdit->setPlainText(exampleXML);
            m_statusLabel->setText("使用默认示例XML (未找到input.xml文件)");
        }
    }

private:
    QTextEdit* m_xmlEdit;
    QPushButton* m_checkButton;
    QLabel* m_statusLabel;
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    
    MainWindow window;
    window.show();
    
    return app.exec();
}

#include "main.moc"
